<?php


namespace App\Http\Controllers\Chat;


use App\Http\Controllers\Controller;
use App\Models\ChatMessage;
use App\Models\ChatRoomUser;
use Illuminate\Http\Request;

class ChatMessageController extends Controller
{
    public function index(Request $request)
    {
        $query = ChatMessage::where('room_id', $request->input('room_id'));
        if ($request->input('read_message_id')) {
            $query->where('id', '>', $request->input('read_message_id'));
        }
        $data = $query->paginate(30)->toArray();
        $count = count($data['data']);
        if($count > 0){
            ChatRoomUser::saveReadMessageID( $request->user()->id, $request->input('room_id'), $data['data'][$count-1]['id']);
        }
        return $this->response($data);
    }

    public function store(Request $request, ChatMessage $obj)
    {
        $all = $request->all();
        $obj->fill($all);
        $obj->user_id = $request->user()->id;
        $obj->save();
        ChatRoomUser::saveReadMessageID($request->user()->id, $request->input('room_id'), $obj->id);
        return $this->response($obj);
    }
}
